﻿using System;

using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.PlatFormException;
using Sunyi.Project.WebPoint.ServiceAccess;

namespace Sunyi.Project.WebPoint.BusinessLogic
{
    public partial class TokenServiceManager
    {
        TokenManager tokenManager = new TokenManager();

        public Token IssueToken(string userName, string password)
        {
            Token token = null;
            var authenticationManager = new AuthenticationManager();

            if (authenticationManager.ValidateUser(userName, password))
            {
                token = tokenManager.SelectByUserName(userName);

                if (token == null)
                {
                    var userManager = new UserManager();
                    var user = userManager.SelectByName(userName);

                    if (user != null)
                    {
                        token = ServiceAccessHelper.GenerateToken(user.Id, user.UserName);
                        tokenManager.Insert(token);
                    }
                }
            }

            return token;
        }

        public Token GetToken(Guid tokenId, string accessCode)
        {
            var token = tokenManager.Select(tokenId);

            if (token != null && (!token.IsActive || token.IsExpired)) { tokenManager.Erasure(token.Id); token = null; }

            if (token == null)
            {
                ExceptionGenerator.ThrowInvalidTokenId(tokenId);
            }

            if (!ServiceAccessHelper.ValidateAccessCode(token.SecurityKey, accessCode))
            {
                token = null;

                ExceptionGenerator.ThrowInvalidAccessCode(tokenId, accessCode);
            }

            return token;
        }

        public void RemoveToken(Guid tokenId, string accessCode)
        {
            var token = tokenManager.Select(tokenId);

            if (token == null)
            {
                ExceptionGenerator.ThrowInvalidTokenId(tokenId);
            }

            if (!ServiceAccessHelper.ValidateAccessCode(token.SecurityKey, accessCode))
            {
                ExceptionGenerator.ThrowInvalidAccessCode(tokenId, accessCode);
            }

            tokenManager.Erasure(tokenId);
        }

        public bool VerifyAccessCode(string userName, string accessCode)
        {
            var tokenManager = new TokenManager();

            return tokenManager.VerifyUser(userName, accessCode);
        }
    }
}
